package com.hnist.empdemo.view.component;

import com.hnist.empdemo.common.Constant;
import com.hnist.empdemo.pojo.Department;
import com.hnist.empdemo.pojo.Employee;
import com.hnist.empdemo.pojo.Position;
import com.hnist.empdemo.service.Impl.employServiceImpl;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;

import java.util.List;

public class AddEmployeeDialog {
    private Stage dialogStage;
    private TableView<Employee> employeeTable;

    // 输入字段
    private TextField idField;
    private TextField nameField;
    private ComboBox<String> genderComboBox;
    private ComboBox<String> departmentComboBox;
    private ComboBox<String> positionComboBox;
    private TextField salaryField;
    private TextField bonusField;

    public AddEmployeeDialog(Window owner, TableView<Employee> employeeTable) {
        this.employeeTable = employeeTable;
        this.dialogStage = new Stage();
        this.dialogStage.initOwner(owner);
        this.dialogStage.setTitle("新增员工");
        this.dialogStage.initModality(Modality.WINDOW_MODAL);
        this.dialogStage.setResizable(false);
        this.dialogStage.setWidth(500);
        this.dialogStage.setHeight(500);

        initLayout();
    }

    private void initLayout() {
        VBox mainContainer = new VBox(20);
        mainContainer.setPadding(new Insets(20));
        mainContainer.setAlignment(Pos.CENTER);

        // 表单网格布局
        GridPane formGrid = new GridPane();
        formGrid.setHgap(15);
        formGrid.setVgap(15);
        formGrid.setAlignment(Pos.CENTER);

        // 初始化输入组件
        idField = new TextField();
        idField.setPromptText("自动生成可留空");
        idField.setPrefWidth(200);

        nameField = new TextField();
        nameField.setPromptText("请输入姓名（必填）");
        nameField.setPrefWidth(200);

        genderComboBox = new ComboBox<>();
        genderComboBox.getItems().addAll("男", "女");
        genderComboBox.setPromptText("请选择");
        genderComboBox.setPrefWidth(200);

        // 加载部门数据
        departmentComboBox = new ComboBox<>();
        departmentComboBox.setPromptText("请选择");
        List<Department> departments = employServiceImpl.getInstance().listAllDeptOrPosOrEmpInfo(Department.class);
        departments.forEach(dept -> departmentComboBox.getItems().add(dept.getName()));
        departmentComboBox.setPrefWidth(200);

        // 加载职位数据
        positionComboBox = new ComboBox<>();
        positionComboBox.setPromptText("请选择");
        List<Position> positions = employServiceImpl.getInstance().listAllDeptOrPosOrEmpInfo(Position.class);
        positions.forEach(pos -> positionComboBox.getItems().add(pos.getName()));
        positionComboBox.setPrefWidth(200);

        salaryField = new TextField();
        salaryField.setPromptText("请输入薪资");
        salaryField.setPrefWidth(200);

        bonusField = new TextField();
        bonusField.setPromptText("请输入奖金");
        bonusField.setPrefWidth(200);

        // 表单布局赋值


        formGrid.add(new Label("员工ID:"), 0, 0);
        formGrid.add(idField, 1, 0);

        formGrid.add(new Label("员工姓名:"), 0, 1);
        formGrid.add(nameField, 1, 1);

        formGrid.add(new Label("性别:"), 0, 2);
        formGrid.add(genderComboBox, 1, 2);

        formGrid.add(new Label("部门:"), 0, 3);
        formGrid.add(departmentComboBox, 1, 3);

        formGrid.add(new Label("职位:"), 0, 4);
        formGrid.add(positionComboBox, 1, 4);

        formGrid.add(new Label("薪资:"), 0, 5);
        formGrid.add(salaryField, 1, 5);

        formGrid.add(new Label("奖金:"), 0, 6);
        formGrid.add(bonusField, 1, 6);


        // 按钮区域
        HBox buttonBox = new HBox(20);
        buttonBox.setPadding(new Insets(10, 0, 0, 0));
        buttonBox.setAlignment(Pos.CENTER);

        Button confirmBtn = new Button("确认添加");
        confirmBtn.setPrefWidth(100);
        Button cancelBtn = new Button("取消");
        cancelBtn.setPrefWidth(50);

        confirmBtn.setOnAction(e -> handleConfirm());
        cancelBtn.setOnAction(e -> dialogStage.close());

        buttonBox.getChildren().addAll(confirmBtn, cancelBtn);

        mainContainer.getChildren().addAll(formGrid, buttonBox);

        Scene scene = new Scene(mainContainer);
        dialogStage.setScene(scene);
    }

    private void handleConfirm() {
        // ID 校验
        String idText = idField.getText().trim();
        Integer id = null;
        if (!idText.isEmpty()) {
            try {
                id = Integer.parseInt(idText);
            } catch (NumberFormatException e) {
                showAlert(Alert.AlertType.ERROR, "格式错误", "ID必须为整数");
                return;
            }

            // 检查ID是否已存在
            if (employServiceImpl.getInstance().isEmployeeIdExists(id)) {
                showAlert(Alert.AlertType.WARNING, "警告", "该员工ID已存在，请重新输入");
                return;
            }
        }

        // 基础校验
        String name = nameField.getText().trim();
        if (name.isEmpty()) {
            showAlert(Alert.AlertType.WARNING, "警告", "员工姓名不能为空");
            return;
        }

        String gender = genderComboBox.getValue();
        if (gender == null || gender.isEmpty()) {
            showAlert(Alert.AlertType.WARNING, "警告", "请选择性别");
            return;
        }

        String department = departmentComboBox.getValue();
        if (department == null || department.isEmpty()) {
            showAlert(Alert.AlertType.WARNING, "警告", "请选择部门");
            return;
        }

        String position = positionComboBox.getValue();
        if (position == null || position.isEmpty()) {
            showAlert(Alert.AlertType.WARNING, "警告", "请选择职位");
            return;
        }

        // 数字字段校验
        double salary = 0;
        if (!salaryField.getText().trim().isEmpty()) {
            try {
                salary = Double.parseDouble(salaryField.getText().trim());
            } catch (NumberFormatException e) {
                showAlert(Alert.AlertType.ERROR, "格式错误", "薪资必须为数字");
                return;
            }
        }

        double bonus = 0;
        if (!bonusField.getText().trim().isEmpty()) {
            try {
                bonus = Double.parseDouble(bonusField.getText().trim());
            } catch (NumberFormatException e) {
                showAlert(Alert.AlertType.ERROR, "格式错误", "奖金必须为数字");
                return;
            }
        }

        // 构建员工对象
        Employee employee = new Employee();
        if (!idField.getText().trim().isEmpty()) {
            try {
                employee.setId(Integer.parseInt(idField.getText().trim()));
            } catch (NumberFormatException e) {
                showAlert(Alert.AlertType.ERROR, "格式错误", "ID必须为整数");
                return;
            }
        }

        employee.setName(name);
        employee.setGender(gender);
        employee.setDepartment(department);
        employee.setPosition(position);
        employee.setSalary(salary);
        employee.setBonus(bonus);

        // 调用服务层添加
        boolean success = employServiceImpl.getInstance().addEmployee(employee);
        if (success) {
            showAlert(Alert.AlertType.INFORMATION, "成功", Constant.DATA_ADD_SUCCESS);
            // 刷新表格数据
            employeeTable.getItems().add(employee);
            dialogStage.close();
        } else {
            showAlert(Alert.AlertType.ERROR, "失败", Constant.DATA_DUPLICATE_ERROR);
        }
    }

    private void showAlert(Alert.AlertType type, String title, String content) {
        Alert alert = new Alert(type);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.initOwner(dialogStage);
        alert.showAndWait();
    }

    public void show() {
        dialogStage.showAndWait();
    }
}